<script setup lang='ts'>
	import {onLoad, onReachBottom, onShareAppMessage, onShareTimeline, onUnload, onPullDownRefresh} from '@dcloudio/uni-app'
	import { getClassListAPI } from '@/api/api.js';
	import { ref } from 'vue';
	
	const classList = ref([])
	const queryParams = ref({
		pageNum: 1,
		pageSize: 12
	})
	// 是否停止发送网络请求
	const stop = ref(false)
	  
	// 获取分类列表网络请求函数  
	async function getClassList() {
		const res = await getClassListAPI(queryParams.value)
		// console.log(res);
		if (res.data.length < queryParams.value.pageSize) stop.value = true
		classList.value = [...classList.value, ...res.data]
		// console.log(classList.value);
		// 存入storage
		uni.setStorageSync('classListStorage', classList.value)
	}
	
	let pageName;
	onLoad((e) => {
		console.log(e);
		if (e.type) queryParams.value.type = e.type
		pageName = e.name
		if (e.id) queryParams.value.classid = e.id
		getClassList()
		
		// 动态设置当前页面的标题
		uni.setNavigationBarTitle({
			title: e.name
		})
	})
	
	// 触底加载更多
	onReachBottom(() => {
		if (stop.value) return
		queryParams.value.pageNum++
		getClassList()
	})
	
	// 分享给好友
	onShareAppMessage((e) => {
		return {
			title: `岁月壁纸-${pageName}`,
			path: `/pages/classList/classList?id=${queryParams.classid}&name=${pageName}` ,
		}
	})
	
	// 分享朋友圈
	onShareAppMessage((e) => {
		return {
			title: `岁月壁纸-${pageName}`,
			// 不需要携带前面的路径
			query: `id=${queryParams.classid}&name=${pageName}`
		}
	})
	
	// 离开页面，清空缓存
	onUnload(() => {
		uni.removeStorageSync('classListStorage')
	})
	
	// 下拉刷新
	onPullDownRefresh(() => {
		// 清空累加的数据
		classList.value = []
		getClassList()
		uni.stopPullDownRefresh()
	})
</script>


<template>
	<view class="class-list">
		<view class="loading" v-if="!classList.length && !stop">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		<view class="content">
			<navigator :url="`/pages/preview/preview?id=${item._id}`" class="item" v-for="item,index in classList" :key="item._id">
				<image class="img" :src="item.smallPicurl" mode="widthFix"></image>
			</navigator>
		</view>
		<view class="loading" v-if="classList.length || stop">
			<uni-load-more :status="stop ? 'onMore' : 'loading'"></uni-load-more>
		</view>
		<!-- 小程序安全区域 -->
		<view class="safe-area-inset-bottom">
			
		</view>
	</view>
</template>


<style scoped lang='scss'>
	.class-list{
		.content{
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 5rpx;
			padding:5rpx;
			.item{
				.img{
					display: block;
					width: 100%;
					height: 100%;
				}
			}
		}
	}
</style>
